from obs.spider import source_code_spider, package_revision_spider
import os
import hashlib
from pprint import pprint
from time import sleep
import subprocess


def calculate_md5(directory):
    # 创建一个空的字典来存储文件名和MD5值
    file_md5 = {}

    # 遍历文件夹
    for filename in os.listdir(directory):
        filepath = os.path.join(directory, filename)

        # 只处理文件，不处理子文件夹
        if os.path.isfile(filepath):
            # 打开文件
            with open(filepath, 'rb') as f:
                # 计算文件的MD5值
                md5 = hashlib.md5(f.read()).hexdigest()

            # 将文件名和MD5值添加到字典中
            file_md5[filename] = md5

    return file_md5


def get_file_sizes(directory_path):
    # 初始化一个空字典来存储文件大小
    file_sizes = {}

    # 遍历指定目录下的所有文件
    for file in os.listdir(directory_path):
        # 获取文件的完整路径
        file_path = os.path.join(directory_path, file)

        # 检查这是一个文件，不是目录
        if os.path.isfile(file_path):
            # 获取文件的大小，并存储在字典中
            file_sizes[file] = os.path.getsize(file_path)

    return file_sizes


def get_commit_hashes(repo_path, branch_name):
    # 切换到repo路径
    os.chdir(repo_path)

    # 使用git log获取所有的commit hash
    result = subprocess.run(['git', 'log', branch_name, '--pretty=format:%H'], stdout=subprocess.PIPE)

    # 将结果从bytes转换为str，并使用换行符分割
    commit_hashes = result.stdout.decode('utf-8').split('\n')

    return commit_hashes


def map_revision_commit(project_name: str, package_name: str, branch: str, files):
    os.chdir(f'../../clone_repo/{package_name}')
    os.system(f'git switch {branch} && git pull')

    file_md5 = {}
    file_size = {}
    for k, v in files.items():
        file_md5[k] = v['md5']
        file_size[k] = v['size']
    # pprint(file_md5)
    # pprint(file_size)

    commits = get_commit_hashes(f'../../clone_repo/{package_name}', branch)
    for commit in commits:
        os.system(f'git checkout {commit}')
        print(f'Trying commit: {commit}')

        git_md5 = calculate_md5('.')
        # pprint(git_md5)
        git_size = get_file_sizes('.')
        # pprint(git_size)

        if set(git_md5.keys()) == set(files.keys()):
            # File count and names are identical
            print('\n\n\nfile count & names ident\n\n\n')

        if git_md5 == file_md5:
            print('\n\n\nMD5 MATCH: WE FOUND IT!!\n\n\n')

        if git_size == file_size:
            print('\n\n\nSIZE MATCH: WE FOUND!!!\n\n\n')

    os.system(f'git checkout {commits[0]}')

    return


if __name__ == '__main__':
    project_name = 'openEuler:22.09'
    architecture_name = 'riscv64'
    package_name = 'mpich'
    revision = 2

    # _service = source_code_spider.get_service_file(project_name, package_name)
    # branch = _service['revision']
    # branch = 'openEuler-22.09-riscv64'
    branch = 'master'
    print(f'Using branch: {branch}')
    files = package_revision_spider.get_revision_detail(project_name, package_name, revision)
    map_revision_commit(project_name, package_name, branch, files)
